package com.ruoyi.business.controller;

import java.io.IOException;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.IdUtil;
import com.ruoyi.business.domain.dto.DailyTrainGroupDTO;
import com.ruoyi.business.domain.vo.DailyTrainVo;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableSupport;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.DailyTrain;
import com.ruoyi.business.service.IDailyTrainService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 每日车次Controller
 * 
 * @author ruoyi
 * @date 2025-03-06
 */
@RestController
@RequestMapping("/business/daily-train")
public class DailyTrainController extends BaseController
{
    @Autowired
    private IDailyTrainService dailyTrainService;

    /**
     * 查询每日车次列表
     */
    @PreAuthorize("@ss.hasPermi('business:daily-train:list')")
    @GetMapping("/list")
    public TableDataInfo list(DailyTrain dailyTrain)
    {
        startPage();
        List<DailyTrain> list = dailyTrainService.selectDailyTrainList(dailyTrain);
        logger.info("所有",list);
        return getDataTable(list);
    }

    /**
     * 导出每日车次列表
     */
    @PreAuthorize("@ss.hasPermi('business:daily-train:export')")
    @Log(title = "每日车次", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DailyTrain dailyTrain)
    {
        List<DailyTrain> list = dailyTrainService.selectDailyTrainList(dailyTrain);
        ExcelUtil<DailyTrain> util = new ExcelUtil<DailyTrain>(DailyTrain.class);
        util.exportExcel(response, list, "每日车次数据");
    }
    /**
     * 导入每日车次列表
     */
    @PreAuthorize("@ss.hasPermi('business:daily-train:add')")
    @Log(title = "每日车次", businessType = BusinessType.IMPORT)
    @PostMapping("/importExcel")
    public AjaxResult importExcel(MultipartFile file) throws IOException {
        ExcelUtil<DailyTrainVo> util = new ExcelUtil<DailyTrainVo>(DailyTrainVo.class);
        List<DailyTrainVo> list = util.importExcel(file.getInputStream());
        List<DailyTrain> dailyTrainList = new ArrayList<>();
        for (DailyTrainVo dailyTrainVo : list) {
            DailyTrain dailyTrain=new DailyTrain();
            dailyTrain.setId(IdUtil.getSnowflakeNextId());
            dailyTrain.setCode(dailyTrainVo.getCode());
            dailyTrain.setDate(dailyTrainVo.getDate());
            dailyTrain.setType(dailyTrainVo.getType());
            dailyTrain.setStart(dailyTrainVo.getStart());
            dailyTrain.setStartPinyin(dailyTrainVo.getStartPinyin());
            dailyTrain.setStartTime(Time.valueOf(dailyTrainVo.getStartTime()));
            dailyTrain.setEnd(dailyTrainVo.getEnd());
            dailyTrain.setEndPinyin(dailyTrainVo.getEndPinyin());
            dailyTrain.setEndTime(Time.valueOf(dailyTrainVo.getEndTime()));
            dailyTrain.setRemark(dailyTrainVo.getRemark());
            dailyTrainList.add(dailyTrain);
        }
        return toAjax(dailyTrainService.insertDailyTrains(dailyTrainList));
    }


    /**
     * 获取每日车次详细信息
     */
    @PreAuthorize("@ss.hasPermi('business:daily-train:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(dailyTrainService.selectDailyTrainById(id));
    }

    /**
     * 新增每日车次
     */
    @PreAuthorize("@ss.hasPermi('business:daily-train:add')")
    @Log(title = "每日车次", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DailyTrain dailyTrain)
    {
        dailyTrain.setId(IdUtil.getSnowflakeNextId());
        return toAjax(dailyTrainService.insertDailyTrain(dailyTrain));
    }

    /**
     * 修改每日车次
     */
    @PreAuthorize("@ss.hasPermi('business:daily-train:edit')")
    @Log(title = "每日车次", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DailyTrain dailyTrain)
    {
        return toAjax(dailyTrainService.updateDailyTrain(dailyTrain));
    }

    /**
     * 删除每日车次
     */
    @PreAuthorize("@ss.hasPermi('business:daily-train:remove')")
    @Log(title = "每日车次", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(dailyTrainService.deleteDailyTrainByIds(ids));
    }

    /**
     * 按车次分组查询每日车次列表
     */
    @PreAuthorize("@ss.hasPermi('business:daily-train:list')")
    @GetMapping("/listByGroup")
    public TableDataInfo listByGroup(DailyTrain dailyTrain) {
        // 获取分页信息
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        
        // 1. 首先获取不同的车次编号列表(分页)
        int offset = (pageNum - 1) * pageSize;
        List<String> trainCodes = dailyTrainService.selectDistinctTrainCodes(dailyTrain, pageSize, offset);
        
        // 2. 获取车次总数
        int total = dailyTrainService.countDistinctTrainCodes(dailyTrain);
        
        // 3. 然后根据分页后的车次编号查询完整的车次数据
        List<DailyTrainGroupDTO> groups = new ArrayList<>();
        if (!trainCodes.isEmpty()) {
            // 设置车次编号列表条件
            dailyTrain.setTrainCodes(trainCodes);
            
            // 查询这些车次的所有车次数据(不分页)
            List<DailyTrain> trains = dailyTrainService.selectDailyTrainByTrainCodes(dailyTrain);
            
            // 按code分组
            Map<String, List<DailyTrain>> trainGroups = trains.stream()
                    .collect(Collectors.groupingBy(DailyTrain::getCode));
            
            // 转换为DTO对象
            for (String code : trainCodes) {
                List<DailyTrain> codeTrains = trainGroups.getOrDefault(code, new ArrayList<>());
                
                if (!codeTrains.isEmpty()) {
                    DailyTrainGroupDTO groupDTO = new DailyTrainGroupDTO();
                    groupDTO.setCode(code);
                    groupDTO.setTrains(codeTrains);
                    
                    // 获取发站和终点站信息（使用第一个车次的信息）
                    DailyTrain firstTrain = codeTrains.get(0);
                    groupDTO.setType(firstTrain.getType());
                    groupDTO.setStart(firstTrain.getStart());
                    groupDTO.setEnd(firstTrain.getEnd());
                    
                    groups.add(groupDTO);
                }
            }
        }
        
        // 4. 返回分页结果
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(groups);
        rspData.setTotal(total);
        rspData.setMsg("查询成功");
        
        return rspData;
    }
}
